package com.jt.blog.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Objects;
import com.jt.blog.common.model.Page;
import com.jt.blog.common.model.Response;
import com.jt.blog.common.util.ExceptionUtil;
import com.jt.blog.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

import static com.google.common.base.Preconditions.checkArgument;

/**
 * @author : 戴瑞
 * @Description :用户service
 * @create : 2017-05-20 11:20
 **/
@Service
public class UserServiceImpl extends AbstractBaseService<User> implements UserService {

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Response<User> login(String account, String password, String ip, Integer back) {
        Response<User> response = new Response<User>();
        try {
            checkArgument(!StringUtils.isEmpty(account), "账号为空");
            Example example = new Example(User.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("account", account);
            List<User> users = (List) mapper.selectByExample(example);
            checkArgument(users != null && users.size() > 0, "账号不存在");
            User user = users.get(0);
            String realPassword = user.getPassword();
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes("utf-8"));
            checkArgument(Objects.equal(md5Password, realPassword), "密码错误");
            checkArgument(Objects.equal(1, user.getStatus()), "账号被冻结，请与管理员联系");
            user.setLastLoginIp(ip);
            user.setLastLoginTime(new Date());
            mapper.updateByPrimaryKeySelective(user);
            response.setResult(user);
        } catch (Exception e) {
            response.setError(e.getMessage());
        }
        return response;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Response<User> register(User user) {
        Response<User> response = new Response<>();
        try {
            checkArgument(!(null == user), "账号为空");
            String account = user.getAccount();
            checkArgument(!StringUtils.isEmpty(account), "账号为空");
            String password = user.getPassword();
            checkArgument(!StringUtils.isEmpty(password), "密码为空");
            String name = user.getName();
            checkArgument(!StringUtils.isEmpty(name), "昵称为空");
            Example example = new Example(User.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("account", account);
            example.or();
            criteria.andEqualTo("name", name);
            List users = (List) mapper.selectByExample(example);
            checkArgument(users == null || users.size() < 1, "账号已存在");
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes("utf-8"));
            user.setPassword(md5Password);
            user.setStatus(1);
            mapper.insert(user);
            response.setResult(user);
        } catch (Exception e) {
            response.setError(e.getMessage());
        }
        return response;
    }

    /**
     * 修改用户密码
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Response<String> updatePwd(String oldPwd, String newPwd, long id) {
        Response<String> response = new Response<>();
        try {
            checkArgument(!oldPwd.equals(newPwd), "原密码和新密码不能为空");
            oldPwd = DigestUtils.md5DigestAsHex(oldPwd.getBytes("utf-8"));
            newPwd = DigestUtils.md5DigestAsHex(newPwd.getBytes("utf-8"));
            Example example = new Example(User.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("id", id);
            criteria.andEqualTo("password", oldPwd);
            List<User> users = mapper.selectByExample(example);

            checkArgument(users != null && users.size() > 0, "账号不存在");

            // 更新用户密码
            User user = users.get(0);
            user.setPassword(newPwd);
            mapper.updateByPrimaryKeySelective(user);
            response.setResult("密码修改成功");
        } catch (Exception e) {
            response.setError(e.getMessage());
            logger.warn(ExceptionUtil.getStackTrace(e));
        }
        return response;
    }

    /**
     * 根据用户名查询用户
     *
     * @param userName
     * @return
     */
    @Override
    public Response<User> selectByUserName(String userName) {

        Response<User> response = new Response<User>();
        try {
            checkArgument(!(StringUtils.isEmpty(userName)), "用户名为空");
            Example example = new Example(User.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("account", userName);
            List users = (List) mapper.selectByExample(example);
            checkArgument(!(users == null || users.size() < 1), "用户不存在");
            User user = (User) users.get(0);
            response.setResult(user);
        } catch (Exception e) {
            response.setError(e.getMessage());
        }
        return response;
    }

    @Override
    public Response<Page<User>> getAllUser(Page<User> page, User user) {
        Response<Page<User>> response = new Response<>();
        PageHelper.startPage(page.getPageNo(), page.getPageSize(), "id desc");
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(user.getAccount())) {
            criteria.andEqualTo("account", user.getAccount());
        }
        if (StringUtils.isNotEmpty(user.getName())) {
            criteria.andEqualTo("name", user.getName());
        }
        if (user.getStatus() != null && user.getStatus() != -1) {
            // -1 代表查询所有
            criteria.andEqualTo("status", user.getStatus());
        }
        // 0代表普通用户
        criteria.andEqualTo("admin", 0);
        List<User> userList = mapper.selectByExample(example);
        // 创建分页信息对象
        PageInfo<User> temp = new PageInfo<>(userList);
        page.setRows(temp.getList());
        page.setTotal(temp.getTotal());
        page.setPageMax(temp.getLastPage());
        response.setResult(page);
        return response;
    }

    /**
     * 更新用户的状态
     *
     * @param users
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void updateUserStatus(User[] users) {
        for (User user : users) {
            if (user.getStatus() == 1) {
                user.setStatus(0);
            } else if (user.getStatus() == 0) {
                user.setStatus(1);
            }
            mapper.updateByPrimaryKeySelective(user);
        }
    }

    /**
     * 删除用户
     *
     * @param ids
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void deleteUser(Long[] ids) {
        for (Long id : ids) {
            mapper.deleteByPrimaryKey(id);
        }
    }

    /**
     * 更新用户头像
     *
     * @param user
     */

    @Override
    public void updateUserHead(User user) {
        mapper.updateByPrimaryKeySelective(user);
    }

}
